package com.yupi.usercenter.base.model;


import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

@CrossOrigin
public class BaseController {
    @Autowired
    protected HttpServletRequest request;
    @Autowired
    protected HttpServletResponse response;

    protected final Integer exportMaxRows = 50000;

    public BaseController() {
    }

    public <T> ApiResult<T> successApi(T object, String version) {
        return ApiResult.success(object, version);
    }

    public <T> ApiResult<T> successApi(Map<Object, String> obj) {
        return ApiResult.success(obj);
    }

    public Result<Void> success() {
        return Result.success();
    }

    public Result<Void> success(Integer code, String msg) {
        return Result.success(code, msg);
    }

    public <T> Result<T> success(T object) {
        return Result.success(object);
    }

    public Result<Void> fail(Integer code, String msg) {
        return Result.error(code, msg);
    }

    public Result<Void> fail() {
        return Result.error(ResultCodeEnum.SYSTEM_INNER_ERROR);
    }

    protected <T> Page<T> getPage() {
        return this.getPage(false);
    }

    protected <T> Page<T> getPage(boolean openSort) {
        int index = 1;
        Integer current = TypeUtils.castToInt(this.request.getParameter("current"), Integer.valueOf(index));
        Integer size = TypeUtils.castToInt(this.request.getParameter("size"), 20);
        Boolean searchCount = TypeUtils.castToBoolean(this.request.getParameter("searchCount"), true);
        size = size > 100 ? 100 : size;
        Page<T> p = new Page((long)current, (long)size, searchCount);
        if (openSort) {
//            p.setAsc(this.getParameterSafeValues("ascs"));
//            p.setDesc(this.getParameterSafeValues("descs"));
        }

        return p;
    }

    protected String[] getParameterSafeValues(String parameter) {
        return AntiSQLFilter.getSafeValues(this.request.getParameterValues(parameter));
    }
}
